package com.example.myactspringboot.server;

import com.example.myactspringboot.bean.Attachment;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static org.springframework.util.FileCopyUtils.BUFFER_SIZE;

/**
 * @Author Zhouchb
 * @Create 2024-04-18 21:02
 * @Description
 */
@Service
public class ExportZIPService {


    /**
     * @return    suffix  目录名称      pathName  目录根路径
     * @Date 2021/6/30 14:11Direc
     * @Author jiangheng
     * @Description //TODO  创建一个临时目录
     **/
    public static java.nio.file.Path createDirectory(String suffix, String pathName) {
        java.nio.file.Path path1 = Paths.get(pathName + "/" + suffix);
        //判断目录是否存在
        boolean pathExists = Files.exists(path1, new LinkOption[]{LinkOption.NOFOLLOW_LINKS});
        if (pathExists) {
            return path1;
        }
        try {
            path1 = Files.createDirectory(path1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path1;
    }
    /**
     * @return      OriginalPathName   源文件    path  目标文件地址    pathName  根目录
     * @Date 2021/6/30 15:11
     * @Author jiangheng
     * @Description //TODO  复制文件
     **/
    public static void copyFile(String OriginalPathName, java.nio.file.Path path, String pathName) {
        java.nio.file.Path originalPath = Paths.get(pathName + "/" + OriginalPathName);
        try {
            Files.copy(originalPath, path,
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * @return   attachments  这个参数主要是从数据库中获取文件的信息，这里可以根据自己的需求更改
     * @Date 2021/6/30 17:31
     * @Author jiangheng
     * @Description //TODO 向文件夹中添加文件
     **/
    public static void addFile(List<Attachment> attachments, String path, String pathName) {
        //遍历所有的文件
        int i = 0;
        for (Attachment attachment : attachments) {
            i++;
            String type = "." + attachment.getFileType();
            java.nio.file.Path targetPath = Paths.get(path + i + type);
            copyFile(attachment.getFilePath(), targetPath, pathName);
        }
    }

    public  void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
            long end = System.currentTimeMillis();
            System.out.println("压缩完成，耗时：" + (end - start) + " ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure)
            throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        if (sourceFile.isFile()) {
            // 向zip输出流中添加一个zip实体，构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if (KeepDirStructure) {
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件，不需要文件的copy
                    zos.closeEntry();
                }
            } else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意：file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即：所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(), KeepDirStructure);
                    }
                }
            }
        }
    }
    /**
     * 下载文件流
     * @param response
     * @param fileName
     * @param inputData
     * @throws IOException
     */
    public static void downloadFile(HttpServletResponse response, String fileName, InputStream inputData) throws IOException {

        BufferedInputStream bins = new BufferedInputStream(inputData);//放到缓冲流里面
        OutputStream outs = response.getOutputStream();//获取文件输出IO流
        BufferedOutputStream bouts = new BufferedOutputStream(outs);
        response.setContentType("application/x-download");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        //开始向网络传输文件流
        while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
            bouts.write(buffer, 0, bytesRead);
        }
        bouts.flush();//这里一定要调用flush()方法
        inputData.close();
        bins.close();
        outs.close();
        bouts.close();

    }
    public  void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] subFiles = file.listFiles();
            if (subFiles != null) {
                for (File subFile : subFiles) {
                    deleteFile(subFile);
                }
            }
            if (file.exists())
                file.delete(); // 删除文件夹
        } else {
            if (file.exists())
                file.delete();
        }
    }
    /**
     * @return
     * @Date 2021/7/1 14:55
     * @Author jiangheng
     * @Description //TODO  删除目录及文件
     **/
    public  void deleteDirAndFiles(File file) {
        File[] files = file.listFiles();
        if (files != null && files.length > 0) {
            for (File f : files) {
                deleteDirAndFiles(f);
            }
        }
        file.delete();
        System.out.println("删除成功" + file.getName());
    }

   static String rootPath = "E:\\新建文件夹";
    public static void main(String[] args) throws IOException {

        // 判断附件表不是空的,则进行下载文件到对应的文件夹下

       List<Attachment> attachments = new ArrayList<>();
        Attachment attachment = new Attachment("11","https://youcourses.gtcfla.net/newresource/82390860-4e3d-4638-99a9-c8c78f0be1f1.jpg","课程思政作品展板.jpg",new ArrayList<>());
        ArrayList<Attachment> objects = new ArrayList<>();
        Attachment attachment3 = new Attachment("33","https://youcourses.gtcfla.net/newresource/82390860-4e3d-4638-99a9-c8c78f0be1f1.jpg","课程思政作品展板.jpg",new ArrayList<>());
        Attachment attachment4 = new Attachment("44","https://youcourses.gtcfla.net/newresource/82390860-4e3d-4638-99a9-c8c78f0be1f1.jpg","课程思政作品展板.jpg",new ArrayList<>());
        objects.add(attachment3);objects.add(attachment4);
        Attachment attachment1 = new Attachment("22","https://youcourses.gtcfla.net/newresource/82390860-4e3d-4638-99a9-c8c78f0be1f1.jpg","思政作品展板.jpg",objects);
        attachments.add(attachment); attachments.add(attachment1);
        String s = System.currentTimeMillis() + "";
        createDirectory(s,rootPath);
        createTemp(attachments, rootPath+"\\"+s);

    }

  static   RestTemplate restTemplate = new RestTemplate();
    public static void createTemp(List<Attachment> attachments,String rootPath) throws IOException {
        for (Attachment attachment : attachments) {
            createDirectory(attachment.getTitle(),rootPath);
            // 配置文件进行读取
            ResponseEntity responseEntity = restTemplate.exchange("https://youcourses.gtcfla.net/newresource/82390860-4e3d-4638-99a9-c8c78f0be1f1.jpg",
                    HttpMethod.GET, null, byte[].class);
            byte[] fileContent = (byte[]) responseEntity.getBody();
            // 利用 File 对象，然后使用 getName() 方法获取文件名（不包括路径）。
            File file = new File(attachment.getFileName());
            String filenameWithoutPrefix = file.getName();
            Files.write(Paths.get(rootPath+"\\"+attachment.getTitle()+"\\" + filenameWithoutPrefix), fileContent);
            if (attachment.getChildre().size()>0){
                createTemp(attachment.getChildre(),rootPath+"\\"+attachment.getTitle());
            }
        }
    }
}
